#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<mysql/mysql.h>

int add(MYSQL *mysql){
	char *sql="insert into test_tb values(null,18,'小张',77.5);";
	int ret=mysql_query(mysql,sql);
	if(ret!=0){
		printf("query sql failed:%s\n",mysql_error(mysql));
		return -1;
	}
	return 0;
}
int mod(MYSQL *mysql){
	char *sql="update test_tb set name='小王' where id=2;";
	int ret=mysql_query(mysql,sql);
	if(ret!=0){
		printf("query sql failed:%s\n",mysql_error(mysql));
		return -1;
	}
	return 0;
}
int del(MYSQL *mysql){
	char *sql="delete from test_tb where id=2;";
	int ret=mysql_query(mysql,sql);
	if(ret!=0){
		printf("query sql failed:%s\n",mysql_error(mysql));
		return -1;
	}
	return 0;
}
int get(MYSQL *mysql){
	//mysql操作句柄初始化
	char *sql="select * from test_tb;";
	int ret=mysql_query(mysql,sql);
	if(ret!=0){
		printf("query sql failed:%s\n",mysql_error(mysql));
		return -1;
	}
	//保存结果集到本地
	MYSQL_RES *res=mysql_store_result(mysql);
	if(res==NULL){
		printf("store result failed : %s\n",mysql_error(mysql));
		return -1;
	}
	//获取结果集中的行数和列数
	int row_num=mysql_num_rows(res);
	int col_num=mysql_num_fields(res);
	//遍历结果集,获取每一行数据(每一行数据都是一个字符串数组)
	for(int i=0;i<row_num;i++){
		MYSQL_ROW row=mysql_fetch_row(res);
		for(int j=0;j<col_num;j++){
			printf("%s\t",row[j]);
		}
		printf("\n");
	}
	//释放结果集
	mysql_free_result(res);
	return 0;
}
int main(){
	//初始化操作句柄
	MYSQL *mysql=mysql_init(NULL);
	//连接mysql数据库
	if(mysql_real_connect(mysql,"127.0.0.1","root","","test_db",0,NULL,0)==NULL){
		printf("connect mysql server failed!\n");
		return -1;
	}
	//设置客户端字符集
	mysql_set_character_set(mysql,"utf8");
	//add(mysql);
	//mod(mysql);
	//del(mysql);
	get(mysql);

	//关闭数据库客户端连接,销毁句柄
	mysql_close(mysql);
	return 0;
}
